const path = require('path');
const Server = require('@chmac/node-git-server');
const { loadRepoInfo } = require('./git-server-service');
const UserService = require('./service/user.service');
const { GIT_PATH } = require('./contants');

const repos = new Server(GIT_PATH, {
    autoCreate: true,
    authenticate: ({type, repo, user}, next) => {
        if(type == 'push') {
          user(async (username, password) => {
            const userService = new UserService()
            const userItem = await userService.findOneByUsername(username)
            if (userItem) {
                if (password === userItem.password) {
                    // 判断仓库是否存在
                    repos.exists(`${repo}.git`, isExist => {
                        if (isExist) {
                            next();
                        } else {
                            next('仓库不存在')
                        }
                    })
                } else {
                    next('wrong password');
                }
            } else {
                next('no username');
            }
          });
        } else {
          next();
        }
    }
});

repos.on('push', (push) => {
    push.on('close', async function() {
        const username = push.repo.split('/')[0]
        const repoName = push.repo.split('/')[1]
        const branchName = push.branch
        // 传一个repos，是因为repos上有一些工具函数
        await loadRepoInfo(repos, username, repoName, branchName)

    })
    push.accept()
});

repos.on('fetch', (fetch) => {
    console.log(`fetch ${fetch.commit}`);
    fetch.accept();
});

exports.GitRouter = function(req, res) {
    repos.handle(req, res)
}
exports.repos = repos
